<!--
 * @description 专区/商品设置
 * @author dumeng
 * @date 2021/7/30
 -->
<template>
  <div class="special-area-page">
    <div class="page-title">
      <span class="title">专区/商品设置</span>
    </div>
    <div class="page-main">
      <el-form
        v-show="areaType === 'special'"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <el-form-item label="专区名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入专区名称" />
        </el-form-item>
        <el-form-item label="专区图片" prop="imageType">
          <el-radio-group v-model="form.imageType">
            <el-radio label="0">模板库选择</el-radio>
            <el-radio label="1">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.imageType === '0'" label="">
          <div class="add-image" style="width: 60%; padding-bottom: 0;">
            <div class="add-image-title">
              <span>请选择模板</span>
              <el-button type="text" @click="templateVisible = true">{{ form.areaImg ? '重新选择' : '点击选择' }}</el-button>
            </div>
            <div class="add-image-main">
              <el-image :src="upload4area.view + form.areaImg">
                <div slot="error" class="image-slot">
                  <template>
                    <div class="icon-wrap">
                      <i class="el-icon-plus avatar-uploader-icon" />
                    </div>
                  </template>
                </div>
              </el-image>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-else>
          <el-row :gutter="10">
            <el-col :span="12">
              <div class="add-image">
                <div class="add-image-title">
                  <span>上传专区图片</span>
                </div>
                <image-upload
                  ref="upload4home"
                  :key="upload4area.imagecropperKey"
                  v-model="form.areaImg"
                  :preview-id="form.areaImg"
                  :forever="true"
                  :width="705"
                  :view="upload4area.view"
                  :height="350"
                  :no-circle="true"
                  :no-rotate="false"
                  lang-type="zh"
                  :max-size="200"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="add-image">
                <div class="add-image-title">
                  <span>上传首页图片</span>
                </div>
                <image-upload
                  ref="upload4home"
                  :key="upload4area.imagecropperKey"
                  v-model="form.homeImg"
                  :preview-id="form.homeImg"
                  :forever="true"
                  :width="702"
                  :view="upload4area.view"
                  :height="246"
                  :no-circle="true"
                  :no-rotate="false"
                  lang-type="zh"
                  :max-size="200"
                />
              </div>
            </el-col>
          </el-row>

        </el-form-item>
      </el-form>
      <commodity v-show="areaType === 'commodity'" ref="commodity" :give-id="id" />
      <select-template :visible.sync="templateVisible" @select="selectTemplte" />
      <div class="page-btns">
        <el-button
          type="primary"
          primary
          @click="changeAreaType()"
        >{{ areaType === 'special' ? '商品设置' : '专区设置' }}
        </el-button>
        <el-button type="primary" @click="finish">配置完成</el-button>
        <el-button plain @click="$emit('setStep', 1)">上一步</el-button>
      </div>
    </div>
    <!-- 发布时的弹窗 -->
    <el-dialog
      v-el-drag-dialog
      title="提示"
      custom-class="sendDialog"
      :show-close="false"
      :visible.sync="sendVisible"
      width="550px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div class="s-top">
        <div class="top-items">
          <div class="t-item">
            <div class="num">{{ chooseItem.issueCoinTotal || '0' }}</div>
            <div class="text">
              <span v-if="chooseItem.classifType==='0' || chooseItem.classifType==='2' || chooseItem.classifType==='8'">发放总金额</span>
              <span v-if="chooseItem.classifType==='1' || chooseItem.classifType==='7' ">发放总张数</span>
            </div>
          </div>
          <div class="t-item">
            <div class="num">{{ chooseItem.issuePersonnelTotal || '0' }}</div>
            <div class="text">发放总人数</div>
          </div>
        </div>
        <div v-if="chooseItem.alreadyList && chooseItem.alreadyList.length>0" class="top-list">
          <div v-for="(item,i) in chooseItem.alreadyList" :key="i" class="list-item">
            <div class="item-item"><span class="item-text">红包金额（每人）： </span> {{ item.issueCoinTotal || '0' }}</div>
            <div class="item-item"><span class="item-text">红包人数（人）： </span>  {{ item.issuePersonnelTotal || '0' }}</div>
          </div>
        </div>
      </div>
      <div class="s-bottom">
        <div class="b-item">
          <div class="name">福利名称：</div>
          <div class="value">{{ chooseItem.giveName || '' }}</div>
        </div>
        <div class="b-item">
          <div class="name">福利领取起止时间：</div>
          <div class="value">{{
            (chooseItem['receiveStarttime'] && chooseItem['receiveStarttime']) + '至' + (
              chooseItem['receiveEndtime'] && chooseItem['receiveEndtime']) || ''
          }}
          </div>
        </div>
        <div class="b-item">
          <div class="name">福利使用起止时间：</div>
          <div class="value">{{
            (chooseItem['expirationStartdate'] && chooseItem['expirationStartdate']) + '至' + (
              chooseItem['expirationDate'] && chooseItem['expirationDate']) || ''
          }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePublish('')">不发布</el-button>
        <el-button
          style="background-color: #EB523C;color:#fff;"
          @click="handlePublish('GIPSTSTUS01')"
        >发布并发放所有人员</el-button>
      </span>
    </el-dialog>
    <el-dialog
      custom-class="tipDialog"
      title="提示"
      :visible.sync="dialogTipVisible"
      width="420px"
    >
      <p style="color: #333;font-size: 14px">{{ tipMsg || '' }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTipVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSetting">去设置</el-button>
        <el-button type="primary" @click="getWelfareActivityView">已完成</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commodity from '../../pages/commodity'
import SelectTemplate from '../template/index'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { createArea, getWelfareActivityView, updateArea, updatePublish } from '../../api'

export default {
  name: 'SpecialArea',
  components: { commodity, SelectTemplate },
  directives: { elDragDialog },
  props: {
    id: {
      type: String,
      default: '111'
    },
    info: {
      type: Object,
      default: () => {
      }
    },
    // 福利名称 默认给专区名称赋值
    giveName: {
      type: String,
      default: ''
    },
    // 是否设置人员
    isSetPerson: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      areaType: 'special',
      form: {
        id: '',
        areaName: '',
        imageType: '0',
        areaImg: '',
        homeImg: ''
      },
      rules: {
        areaName: [
          { required: true, message: '请输入专区名称', trigger: 'blur' }
        ],
        imageType: [
          { required: true, message: '请选择专区图片类型', trigger: 'change' }
        ]
      },
      templateImg: '',
      upload4area: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      templateVisible: false,
      dialogTipVisible: false,
      tipMsg: '',
      tipNext: 0, // 0:还未设置人员、专区与商品 1：还未设置专区与商品 2：还未设置商品 3：全部配置完成
      sendVisible: false,
      chooseItem: {}
    }
  },
  created() {
    this.form.areaName = this.giveName
    for (const i in this.form) {
      if (this.info.hasOwnProperty(i)) {
        this.form[i] = this.info[i]
      }
    }
  },
  methods: {
    changeAreaType() {
      if (this.areaType === 'special') {
        if (this.form.areaName === '' || this.form.areaImg === '' || this.form.homeImg === '') {
          this.$message({
            message: '请完成专区配置！',
            type: 'warning'
          })
          return
        }
        this.settingArea().then(() => {
          this.areaType = 'commodity'
        })
      } else {
        this.areaType = 'special'
      }
    },
    /**
     * 选择模板
     * @param json
     */
    selectTemplte(json) {
      try {
        const obj = JSON.parse(json)
        this.form.areaImg = obj[0].content
        this.form.homeImg = obj[1].content
      } catch (err) {
        this.$message({
          title: '提示',
          message: '模板数据有误，请重试！',
          type: 'error',
          duration: 1500
        })
        return
      }
      this.templateVisible = false
    },
    /**
     * 配置完成
     */
    finish() {
      // 没设置专区
      if (this.form.areaName === '' || this.form.areaImg === '' || this.form.homeImg === '') {
        this.$message({
          message: '请完成专区配置！',
          type: 'warning'
        })
        return
      }
      if (this.isSetPerson === false && this.$refs.commodity.commodityList.length === 0) {
        this.tipMsg = '还未设置人员与商品, 是否配置完成?'
        this.tipNext = 0
        this.dialogTipVisible = true
      } else if (this.$refs.commodity.commodityList.length === 0) {
        this.tipMsg = '还未设置商品, 是否配置完成?'
        this.tipNext = 1
        this.dialogTipVisible = true
      } else if (this.isSetPerson === false) {
        this.tipMsg = '还未设置人员, 是否配置完成?'
        this.tipNext = 0
        this.dialogTipVisible = true
      } else {
        this.settingArea().then(() => {
          this.getWelfareActivityView()
        })
      }
    },
    /**
     * 去设置
     */
    handleSetting() {
      this.dialogTipVisible = false

      this.settingArea().then(() => {
        if (this.tipNext === 0) {
          this.$emit('setStep', 1)
        } else if (this.tipNext === 1) {
          this.areaType = 'commodity'
        }
      })
    },
    getWelfareActivityView() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getWelfareActivityView({ id: this.id }).then(res => {
          loading.close()
          this.chooseItem = res.data.data || {}
          this.sendVisible = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 新增/编辑专区
     * @returns {Promise<unknown>}
     */
    settingArea() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const param = Object.assign({}, this.form)
      param['param1'] = this.id
      return new Promise((resolve, reject) => {
        if (this.form.id) {
          updateArea(param).then(res => {
            loading.close()
            this.$emit('setInfo', this.form)
            resolve()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        } else {
          createArea(param).then(res => {
            loading.close()
            this.form.id = res.data.data
            this.$emit('setInfo', this.form)
            resolve()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        }
      })
    },
    handlePublish(status) {
      this.settingArea().then(() => {
        if (status) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            updatePublish({ id: this.id, publishStatus: status }).then(res => {
              loading.close()
              this.$message({
                title: '成功',
                message: '配置成功',
                type: 'success',
                duration: 2000,
                onClose: () => {
                  this.$router.push({
                    path: this.$filterPath('index'),
                    query: { t: this.$route.query.t }
                  })
                }
              })
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          this.$router.push({
            path: this.$filterPath('index'),
            query: { t: this.$route.query.t }
          })
        }
      })
    }
  }
}
</script>

<style  lang="scss">
.special-area-page {
  .page-title {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    border-bottom: 1px solid #e5e5e5;

    .title {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .page-main {
    .add-image {
      border: 1px solid #e5e5e5;
      padding: 0 20px 20px;
      border-radius: 4px;

      .add-image-title {
        display: flex;
        align-items: center;
        justify-content: space-between;

        & > span {
          color: #666;
          font-size: 14px;
        }
      }

      .add-image-main {
        display: inline-block;
        position: relative;
        background: #f7f7f8;
        border-radius: 4px;
        margin-bottom: 10px;

        .el-image {
          display: block;
        }

        &:hover {
          border-color: #fe5a61;
        }

        .icon-wrap {
          width: 300px;
          height: 180px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(247, 247, 248, 1);
          border: 1px solid rgba(226, 227, 232, 1);
          border-radius: 4px;

          .avatar-uploader-icon {
            font-size: 48px;
            color: #dadada;
            width: 300px;
            text-align: center;
          }
        }

        img {
          display: block;
          max-width: 400px;
          border-radius: 4px;
        }
      }
    }

    .form {
      width: 70%;
      margin: 20px auto;
    }

    .page-btns {
      margin-top: 20px;
      text-align: center;
      margin-bottom: 20px;
    }
  }
  .tipDialog{
    .el-dialog__footer {
      text-align: center !important;
    }
  }
  .sendDialog{
    .s-top{
      margin: 19px auto 0;
      width: 500px;
      opacity: 1;
      background: linear-gradient(#f25a44 0%, #ef7e46 99%);
      border-radius: 8px ;
      padding-bottom: 5px;
      .top-items{
        height: 74px;
        display: flex;
        justify-content: space-between;
        .t-item{
          height: 100%;
          flex: 1;
          color: #ffffff;
          text-align: center;
          padding-top: 21px;
          .num{
            font-size: 16px;
            font-family: PingFang SC Medium, PingFang SC Medium-Medium;
            font-weight: 500;
          }
          .text{
            margin-top: 5px;
            font-size: 14px;
            font-family: PingFang SC Regular, PingFang SC Regular-Regular;
            font-weight: 400;
          }
        }
      }
      .top-list{
        width: 450px;
        margin: 0 auto 5px auto;
        background: linear-gradient(0deg,#ffffff 0%, #ffffff 92%, #fc9c7e 100%);
        border-top: 6px solid #D8431B;
        opacity: 0.4, filter alpha(opacity=50);
        min-height: 55px;
        border-radius: 0 0 6px 6px;
        padding: 0 20px;
        position: relative;
        &:after{
          position: absolute;
          top: -6px;
          left: -10px;
          content: '';
          height: 12px;
          width: 10px;
          background: #D8431B;
          border-radius: 16px 0 0 16px;
        }
        &:before{
          position: absolute;
          top: -6px;
          right: -10px;
          content: '';
          height: 12px;
          width: 10px;
          background: #D8431B;
          border-radius: 0 16px  16px  0;
        }
        .list-item{
          height: 55px;
          display: flex;
          justify-content: space-between;
          color: #fff;
          border-bottom: 1px solid #eeeeee;
          box-sizing: border-box;
          &:last-child{
            border: none;
          }
          .item-item{
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            font-size: 14px;
            font-family: PingFang SC Regular, PingFang SC Regular-Regular;
            font-weight: 400;
            color: #333333;
            .item-text{
              color: #999999;
            }
          }
        }
      }
    }
    .s-bottom{
      margin: 0 auto 19px;
      width: 500px;
      height: 142px;
      opacity: 1;
      display: flex;
      flex-direction: column;
      .b-item{
        flex: 1;
        display: flex;
        align-items: center;
        font-size: 14px;
        font-family: PingFang SC Regular, PingFang SC Regular-Regular;
        font-weight: 400;
        border-bottom: 1px solid #eee;
        &:last-child{
          border: none;
        }
        .name{
          color: #999999;
        }
        .value{
          color: #333;
          font-weight: bold;
        }
      }
    }
    .el-dialog__footer{
      text-align: center !important;
    }
  }
}
</style>
